package backend.dao;

import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import backend.model.User;

@Repository(value = "UserDao")
public class UserDaoImpl extends HibernateDaoSupport implements UserDao {

	@Autowired
	public UserDaoImpl(SessionFactory sessionFactory) {
		setSessionFactory(sessionFactory);
	}

	public void saveOrUpdate(User user) {
		getHibernateTemplate().saveOrUpdate(user);
	}

	public void delete(User user) {
		getHibernateTemplate().delete(user);
	}

	public User getById(int id) {
		return getHibernateTemplate().get(User.class, id);
	}
	
	public User findByUsernameAndPassword(String username, String password) {
		List<User> users = getHibernateTemplate().findByNamedQueryAndNamedParam("findUserByUsernameAndPassword", 
				new String[] {"username", "password"},
				new Object[] {username, password});
		if (users.size() != 1) {
			return null;
		}
		return users.get(0);
	}
}